package com.dag.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dag.account.constants.*;
import com.dag.account.dao.entity.*;
import com.dag.account.service.*;
import com.dag.common.constants.ActiveStatusEnum;
import com.dag.common.constants.AuditStatusEnum;
import com.dag.common.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 平台操作类
 * @author 孙建
 */
@Service
public class PlatformServiceImpl implements IPlatformService {

    @Autowired
    private IAccountService accountService;
    @Autowired
    private IFundPoolService fundPoolService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IMemberIdentityService memberIdentityService;
    @Autowired
    private IOperateRecordService operateRecordService;

    /** 创建人 */
    private static final String CREATER_ID = "account-service";
    /** 默认初始化id */
    private static final String DEFAULT_INIT_ID = "1";


    /**
     * 开通平台会员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Member openPlatformMember() {
        Member platformMember = queryPlatformMember();
        if(platformMember != null){
            return platformMember;
        }

        Member member = new Member();
        // 固定id
        member.setId(DEFAULT_INIT_ID);
        member.setMemberName("平台");
        member.setMobile("00000000000");
        member.setPhone("");
        member.setProvince("上海");
        member.setCity("上海市");
        member.setArea("青浦区");
        member.setAddress("上海市青浦区华徐公路3029弄28号");
        member.setMemberStatus(ActiveStatusEnum.OPEN.getIndex());
        member.setCreaterId(CREATER_ID);
        member.setCreateTime(new Date());
        member.setUpdateTime(new Date());
        member.setOrgId(CommonConstants.DEFAULT_ORG_ID);
        member.setMerchantId(CommonConstants.DEFAULT_MERCHANT_ID);
        memberService.save(member);

        // 保存平台会员身份
        MemberIdentity identity = new MemberIdentity();
        identity.setId(DEFAULT_INIT_ID);
        identity.setMemberId(member.getId());
        identity.setIdentityType(IdentityTypeEnum.PLATFORM.getIndex());
        identity.setIdentityName(IdentityTypeEnum.PLATFORM.getText());
        identity.setAuditStatus(AuditStatusEnum.AUDIT_APPROVAL.getIndex());
        identity.setCreaterId(CREATER_ID);
        identity.setCreateTime(new Date());
        identity.setUpdateTime(new Date());
        identity.setOrgId(member.getOrgId());
        identity.setMerchantId(member.getMerchantId());
        memberIdentityService.save(identity);
        return member;
    }


    /**
     * 获取平台会员
     */
    @Override
    public Member queryPlatformMember() {
        MemberIdentity memberIdentity = memberIdentityService.queryByIdentityType(IdentityTypeEnum.PLATFORM.getIndex());
        if(memberIdentity != null){
            String memberId = memberIdentity.getMemberId();
            return memberService.getById(memberId);
        }
        return null;
    }


    /**
     * 开通平台账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Account openPlatformAccount() {
        Account platformAccount = queryPlatformAccount(AccountTypeEnum.PLATFORM.getIndex());
        if(platformAccount != null){
            return platformAccount;
        }

        // 查询平台会员
        Member platformMember = queryPlatformMember();

        // 保存账户
        Account account = new Account();
        // 固定id
        account.setId(DEFAULT_INIT_ID);
        account.setMemberId(platformMember.getId());
        account.setAccountType(AccountTypeEnum.PLATFORM.getIndex());
        account.setAccountTypeName(AccountTypeEnum.PLATFORM.getText());
        account.setNature(NatureEnum.PLATFORM.getIndex());
        account.setStatus(AccountStatusEnum.VALID.getIndex());
        account.setTotalAmount(BigDecimal.ZERO);
        account.setBalanceAmount(BigDecimal.ZERO);
        account.setFreezeAmount(BigDecimal.ZERO);
        account.setVersion(0L);
        account.setCreateTime(new Date());
        account.setCreaterId(CREATER_ID);
        account.setOrgId(platformMember.getOrgId());
        account.setMerchantId(platformMember.getMerchantId());
        accountService.save(account);

        // 保存操作记录
        String description = "平台总账户开通啦";
        this.saveOperateRecord(account, OperateEventEnum.OPEN.getText(), description);
        return account;
    }


    /**
     * 开通平台收益账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Account openProfitAccount() {
        Account profitAccount = queryPlatformAccount(AccountTypeEnum.PROFIT.getIndex());
        if(profitAccount != null){
            return profitAccount;
        }

        // 查询平台会员
        Member platformMember = queryPlatformMember();

        // 保存账户
        Account account = new Account();
        // 固定id
        account.setId("2");
        account.setMemberId(platformMember.getId());
        account.setAccountType(AccountTypeEnum.PROFIT.getIndex());
        account.setAccountTypeName(AccountTypeEnum.PROFIT.getText());
        account.setNature(NatureEnum.PLATFORM.getIndex());
        account.setStatus(AccountStatusEnum.VALID.getIndex());
        account.setTotalAmount(BigDecimal.ZERO);
        account.setBalanceAmount(BigDecimal.ZERO);
        account.setFreezeAmount(BigDecimal.ZERO);
        account.setVersion(0L);
        account.setCreateTime(new Date());
        account.setCreaterId(CREATER_ID);
        account.setOrgId(platformMember.getOrgId());
        account.setMerchantId(platformMember.getMerchantId());
        accountService.save(account);

        // 保存操作记录
        String description = "平台收益账户开通啦";
        this.saveOperateRecord(account, OperateEventEnum.OPEN.getText(), description);
        return account;
    }


    /**
     * 查询平台账户
     */
    @Override
    public Account queryPlatformAccount() {
        Account account = new Account();
        account.setAccountType(AccountTypeEnum.PLATFORM.getIndex());
        return accountService.getOne(new QueryWrapper<>(account));
    }


    /**
     * 根据账户类型查询平台账户
     */
    @Override
    public Account queryPlatformAccount(Integer accountType) {
        Account account = new Account();
        account.setAccountType(accountType);
        return accountService.getOne(new QueryWrapper<>(account));
    }

    /**
     * 开通资金池账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FundPool openFundPoolAccount() {
        FundPool fundPool = fundPoolService.getFundPool();
        if(fundPool == null){
            fundPool = new FundPool();
            fundPool.setId(DEFAULT_INIT_ID);
            fundPool.setTotalAmount(BigDecimal.ZERO);
            fundPool.setVersion(0L);
            fundPool.setCreaterId(CREATER_ID);
            fundPool.setCreateTime(new Date());
            fundPool.setOrgId(CommonConstants.DEFAULT_ORG_ID);
            fundPool.setMerchantId(CommonConstants.DEFAULT_MERCHANT_ID);
            fundPoolService.save(fundPool);
        }
        return fundPool;
    }


    /**
     * 保存操作记录
     */
    private void saveOperateRecord(Account account, String eventName, String description) {
        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setObjId(account.getId());
        operateRecord.setObjType(ObjTypeEnum.ACCOUNT.getIndex());
        operateRecord.setCreaterId(account.getUpdaterId());
        operateRecord.setCreaterName("平台");
        operateRecord.setCreateTime(new Date());
        operateRecord.setEventName(eventName);
        operateRecord.setDescription(description);
        operateRecord.setOrgId(account.getOrgId());
        operateRecord.setMerchantId(account.getMerchantId());
        operateRecordService.save(operateRecord);
    }
}
